package chapter_04_singleton.p3_register_singleton;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by CharloYao on 2017/3/23.
 */
public class RegSingleton {

    //登记簿，用来登记所有的实例
    private static Map<String,RegSingleton> map = new HashMap<>();

    protected RegSingleton(){}

    //在类加载的时候添加一个实例到登记簿
    static {
        RegSingleton regSingleton = new RegSingleton();
        map.put(regSingleton.getClass().getName(),regSingleton);
    }

    public static RegSingleton getInstance(String name){
        if(name==null){
            name = "RegSingleton";
        }
        if(map.get(name) == null){
            try {
                map.put(name, (RegSingleton) Class.forName(name).newInstance());
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return map.get(name);
    }
}
